<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" :init-fullscreen="true">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 使用Row和Col实现一行四列布局 -->
      <el-row :gutter="20">
        <!-- 第一行 -->
        <el-col :span="6">
          <el-form-item label="生产单号" prop="no">
            <el-input v-model="formData.no" placeholder="保存时自动生成" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产品" prop="productId">
            <ErpSelectProduct v-model="formData.productId" @select="selectProduct" />
            <!--            <ErpSelectRemoteProduct v-model="formData.productId" @select="selectProduct"/>-->
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产品编码" prop="productBarCode">
            <el-input v-model="formData.productBarCode" placeholder="自动选择" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="产品单位" prop="productUnitName">
            <el-input v-model="formData.productUnitName" placeholder="请输入产品单位" disabled />
          </el-form-item>
        </el-col>

        <!-- 第二行 -->
        <el-col :span="6">
          <el-form-item label="订购数量" prop="orderCount">
            <el-input v-model="formData.orderCount" placeholder="请输入订购数量" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生产数量" prop="produceCount">
            <el-input
              v-model.number="formData.produceCount"
              placeholder="请输入生产数量"
              @input="produceCountInput"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="机器" prop="machineId">
            <ErpSelectMachine v-model="formData.machineId" @change="handleMachineChange" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="模具" prop="mouldId">
            <ErpSelectMould
              v-model="formData.mouldId"
              :mould-ids="machineMouldIds"
              :disabled="!formData.machineId"
              :placeholder="formData.machineId ? '请选择模具' : '请先选择机器'"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="生产人" prop="produceUserId">
            <cascader-user v-model="formData.produceUserId" />
          </el-form-item>
        </el-col>

        <!--        <el-col :span="6">-->
        <!--          <el-form-item label="销售订单编号" prop="salesOrderId">-->
        <!--            <el-input v-model="formData.salesOrderId" placeholder="请输入销售订单编号"/>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="6">
          <el-form-item label="销售订单号" prop="salesOrderNo">
            <el-input v-model="formData.salesOrderNo" placeholder="请输入销售订单号" />
          </el-form-item>
        </el-col>

        <!-- 第三行 -->
        <!--        <el-col :span="6">-->
        <!--          <el-form-item label="附件地址" prop="fileUrl">-->
        <!--            <el-input v-model="formData.fileUrl" placeholder="请输入附件地址"/>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="6">
          <el-form-item label="计划完工日期" prop="planFinishTime">
            <el-date-picker
              v-model="formData.planFinishTime"
              type="date"
              value-format="x"
              placeholder="选择计划完工日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 子表的表单 -->
    <ContentWrap>
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
        <el-tab-pane label="1.所需物料" name="material">
          <!--          <SaleOrderItemForm ref="itemFormRef" :items="formData.items" :disabled="disabled"/>-->
          <ProducePlanMaterialItemForm
            ref="producePlanMaterialItemFormRef"
            :items="formData.materialItems"
            :disabled
          />
        </el-tab-pane>
        <el-tab-pane label="2.工序流程" name="process">
          <!--          <SaleOrderItemForm ref="itemFormRef" :items="formData.items" :disabled="disabled"/>-->
          <ProducePlanProcessItemForm
            ref="producePlanProcessItemFormRef"
            :items="formData.processItems"
            :disabled
          />
        </el-tab-pane>
      </el-tabs>
    </ContentWrap>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {  ProducePlanApi } from '@/api/erp/produce/plan'
import { ProduceMaterialApi } from '@/api/erp/produce/material'
import { ProductApi } from '@/api/erp/product/product'
import { BasicMachineApi } from '@/api/erp/basic/machine'

import ProducePlanMaterialItemForm from './components/ProducePlanMaterialItemForm.vue'
import ProducePlanProcessItemForm from './components/ProducePlanProcessItemForm.vue'
import ErpSelectProduct from '@/views/erp/product/product/components/ErpSelectProduct.vue'
import ErpSelectMachine from '@/views/erp/basic/machine/components/ErpSelectMachine.vue'
import ErpSelectMould from '@/views/erp/basic/mould/components/ErpSelectMould.vue'
import { ProduceProcessApi } from '@/api/erp/produce/process'

/** ERP 生产计划单 表单 */
defineOptions({ name: 'ProducePlanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const disabled = computed(() => formType.value === 'detail')
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  no: undefined,
  productId: undefined,
  productName: undefined,
  productBarCode: undefined,
  productUnitId: undefined,
  productUnitName: undefined,
  orderCount: undefined,
  produceCount: undefined,
  salesOrderId: undefined,
  salesOrderNo: undefined,
  fileUrl: undefined,
  planFinishTime: undefined,
  realFinishTime: undefined,
  remark: undefined,
  machineId: undefined,
  mouldId: undefined,
  produceUserId: undefined,
  materialItems: [],
  processItems: []
} as any)

const formRules = reactive({
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  orderCount: [{ required: true, message: '订购数量不能为空', trigger: 'blur' }],
  produceCount: [{ required: true, message: '生产数量不能为空', trigger: 'blur' }],
  planFinishTime: [{ required: true, message: '计划完工不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('material')
const producePlanMaterialItemFormRef = ref()

/** 模具相关 */
const machineMouldIds = ref<number[]>([]) // 机器绑定的模具ID列表

// 处理机器选择变化
const handleMachineChange = async (machineId: number) => {
  if (machineId) {
    // 获取机器绑定的模具列表
    const machineMoulds = await BasicMachineApi.getBasicMachineMouldListByMachineId(machineId)
    machineMouldIds.value = machineMoulds.map((item: any) => item.mouldId)
    console.log('machineMouldIds.value', machineMouldIds.value)

    // 如果当前选中的模具不在新的列表中，清空选择
    if (formData.value.mouldId && machineMouldIds.value.length > 0 && !machineMouldIds.value.includes(formData.value.mouldId)) {
      formData.value.mouldId = undefined
    }
  } else {
    // 清空机器时，重置模具列表
    machineMouldIds.value = []
    formData.value.mouldId = undefined
  }
}

// // 监听 formData.produceCount 变化（实时触发）
// watch(
//     () => formData.value.produceCount,
//     () => {
//       setBom(formData)
//     },
//     {immediate: false} // immediate: true 表示"初始渲染时就触发一次"，按需开启
// );

/** 打开弹窗 */
const open = async (type: string, id?: number, presetData?: any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProducePlanApi.getProducePlan(id)
      let materialData = await ProduceMaterialApi.getProduceMaterialPage({
        planId: formData.value.id
      })
      formData.value.materialItems = materialData.list
      let processData = await ProduceProcessApi.getProduceProcessPage({ planId: formData.value.id })
      formData.value.processItems = processData.list
    } finally {
      formLoading.value = false
    }
  }

  // 如果有预设的生产计划数据（从生产计划补货传入）
  if (presetData) {
    formData.value.productId = presetData.productId
    formData.value.productName = presetData.productName
    formData.value.productBarCode = presetData.productBarCode
    formData.value.productUnitId = presetData.productUnitId
    formData.value.productUnitName = presetData.productUnitName
    formData.value.produceCount = presetData.produceCount
    formData.value.orderCount = presetData.orderCount

    // 根据库存情况生成备注
    const stockCount = presetData.stockCount || 0
    const shortage = presetData.produceCount - stockCount
    let remarkText = ''
    if (shortage > 0) {
      remarkText = `从生产计划补货（缺货数量：${shortage}，当前库存：${stockCount}）`
    } else {
      remarkText = `从生产计划创建（当前库存：${stockCount}）`
    }
    // 添加关联的生产计划单号
    if (presetData.sourcePlanNo) {
      remarkText += ` - 关联生产单号：${presetData.sourcePlanNo}`
    }
    formData.value.remark = remarkText

    // 设置默认计划完工时间（7天后）
    const now = new Date()
    now.setDate(now.getDate() + 7)
    formData.value.planFinishTime = now.getTime()

    // 自动加载 BOM 物料和工序数据
    if (presetData.productId) {
      await setBom(formData)
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await ProducePlanApi.createProducePlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProducePlanApi.updateProducePlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    no: undefined,
    productId: undefined,
    productName: undefined,
    productBarCode: undefined,
    productUnitId: undefined,
    productUnitName: undefined,
    orderCount: undefined,
    produceCount: undefined,
    salesOrderId: undefined,
    salesOrderNo: undefined,
    fileUrl: undefined,
    planFinishTime: undefined,
    realFinishTime: undefined,
    remark: undefined,
    machineId: undefined,
    mouldId: undefined,
    produceUserId: undefined,
    materialItems: [],
    processItems: []
  }
  formRef.value?.resetFields()
}

const selectProduct = (product) => {
  if (product) {
    console.log(product)
    formData.value.productId = product.id
    formData.value.productBarCode = product.barCode
    formData.value.productUnitId = product.unitId
    formData.value.productUnitName = product.unitName
    formData.value.mouldId = product.mouldId
    setBom(formData)
  }
}

const produceCountInput = () => {
  setBom(formData)
}

/** 加载BOM物料信息 */
const setBom = async (formData: any) => {
  if (!formData.value.productId) {
    return
  }
  const effectiveProduceCount =
    formData.value.produceCount === undefined || formData.value.produceCount === null
      ? 1
      : Number(formData.value.produceCount) // 转为数字，避免字符串相乘（如 '2'*3 虽能运行，但统一类型更严谨）

  const materialData = await ProductApi.getProductBomMaterialPage({
    parentId: formData.value.productId
  })
  console.log(materialData)
  materialData.list.forEach((item) => {
    item.id = null
    const originalCount = item.count === undefined || item.count === null ? 0 : Number(item.count)
    // 计算新 count：原 count * 有效 produceCount
    item.count = originalCount * Number(effectiveProduceCount)
    item.productPrice=item.costPrice
  })

  formData.value.materialItems = materialData.list

  const processData = await ProductApi.getProductBomProcessPage({
    parentId: formData.value.productId
  })
  processData.list.forEach((item) => {
    item.id = null
    item.count = effectiveProduceCount
  })
  formData.value.processItems = processData.list
}
</script>
